package com.star.controller.admin;

import com.star.constant.JwtClaimsConstant;
import com.star.context.BaseContext;
import com.star.dto.*;
import com.star.entity.Admin;
import com.star.properties.JwtProperties;
import com.star.result.PageResult;
import com.star.result.Result;
import com.star.service.AdminService;
import com.star.utils.JwtUtil;
import com.star.vo.admin.AdminLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 管理员管理
 */
@RestController("adminController")
@RequestMapping("/admin")
@Slf4j
// Swagger接口文档
@Api(tags = "管理员端管理接口")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 登录
     *
     * @param adminLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("管理员登录")
    public Result<AdminLoginVO> login(@RequestBody AdminLoginDTO adminLoginDTO) {
        log.info("管理员登录：{}", adminLoginDTO);

        Admin admin = adminService.login(adminLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ADMIN_ID, admin.getId());

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        // 将员工信息缓存到redis中
        String adminToken = "admin_" + admin.getId();
        redisTemplate.opsForValue().set(adminToken,token,1, TimeUnit.DAYS);

        AdminLoginVO adminLoginVO = AdminLoginVO.builder()
                .id(admin.getId())
                .userName(admin.getUsername())
                .name(admin.getName())
                .token(token)
                .avatar(admin.getAvatar())
                .role(admin.getRole())
                .build();

        return Result.success(adminLoginVO);
    }
    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("管理员登出")
    public Result<String> logout() {
        String adminToken = "admin_" + BaseContext.getCurrentId();
        redisTemplate.delete(adminToken);
        return Result.success();
    }
    /**
     * 管理员分页查询
     * @param businessPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("管理员分页查询")
    public Result<PageResult> page(BusinessPageQueryDTO businessPageQueryDTO){
        log.info("管理员分页查询{}", businessPageQueryDTO);
        PageResult pageResult = adminService.pageQuery(businessPageQueryDTO);
        return Result.success(pageResult);
    }
    /**
     * 新增管理员
     * @param adminDTO body参数
     * @return
     */
    @PostMapping
    @ApiOperation("新增管理员")
    public Result<String> addEmployee(@RequestBody AdminDTO adminDTO) {
        log.info("新增管理员{}", adminDTO);
        adminService.add(adminDTO);
        return Result.success();
    }
    /**
     * 启用/禁用管理员状态
     * @param status 路径参数
     * @param id query参数
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("启用/禁用管理员状态")
    public Result<String> updateStatus(@PathVariable Integer status, Long id){
        log.info("启用禁用管理员状态{}{}", status, id);
        adminService.updateStatus(status, id);
        return Result.success();
    }
    /**
     * 根据id查询管理员信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询管理员信息")
    public Result<Admin> getById(@PathVariable Long id){
        log.info("管理员id{}", id);
        Admin admin = adminService.getById(id);
        return Result.success(admin);
    }

    /**
     * 更新管理员信息
     * @param adminDTO body参数
     * @return
     */
    @PutMapping
    @ApiOperation("更新管理员信息")
    public Result<String> update(@RequestBody AdminDTO adminDTO){
        log.info("更新管理员信息{}", adminDTO);
        adminService.update(adminDTO);
        return Result.success();
    }
    /**
     * 修改用户头像
     * @param avatar
     * @return
     */
    @PutMapping("/avatar")
    public Result<String> updateAvatar(@RequestParam Long id, @RequestParam String avatar){
        if(avatar == null || avatar.isEmpty()){
            return Result.error("头像不能为空");
        }
        adminService.updateAvatar(id, avatar);
        return Result.success();
    }
    /**
     * 更新账户密码
     * @param passwordEditDTO
     * @return
     */
    @PutMapping("/editPassword")
    @ApiOperation("更新账户密码")
    public Result<String> updatePwd(@RequestBody PasswordEditDTO passwordEditDTO){
        log.info("修改密码{}", passwordEditDTO);
        adminService.updatePwd(passwordEditDTO);
        String adminToken = "admin_" + passwordEditDTO.getId();
        redisTemplate.delete(adminToken);
        return Result.success();
    }
}
